package com.plugin.gocqhttp.event.impl;

import com.alibaba.fastjson.JSONObject;
import com.plugin.gocqhttp.configuration.GoCqhttpPropertis;
import com.plugin.gocqhttp.event.AbstractEventTypeSupperGenericsSimple;
import com.plugin.gocqhttp.api.GocqApiHttpService;
import com.plugin.gocqhttp.pojo.api.SetRestart;
import com.plugin.gocqhttp.pojo.event.EventHearBeat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;

/**
 * 心跳没接收到 发送推送
 */

@Slf4j
public class EventHeatBeatHandlerImpl extends AbstractEventTypeSupperGenericsSimple<EventHearBeat> {

    public static Long LAST_HEART;
    @Autowired
    private GoCqhttpPropertis goCqhttpPropertis;

    @Autowired
    GocqApiHttpService gocqApiHttpService;

    @PostConstruct
    public void listen(){
        //心跳监听
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (;;){
                    if (null != LAST_HEART && (System.currentTimeMillis() - LAST_HEART > 1000 * 60)){
                        if ( System.currentTimeMillis() - LAST_HEART  > goCqhttpPropertis.getHeartimeout() ){
                            SetRestart setRestart = new SetRestart();
                            setRestart.setNumber(goCqhttpPropertis.getHeartimeout() / 2);
                            gocqApiHttpService.request(setRestart);
                        }
                        log.error("【go-cqhttp】异常");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }).start();
    }

    @Override
    public Object work(JSONObject requestParam, EventHearBeat event) {
        LAST_HEART = System.currentTimeMillis();
        return  null;
    }

//    @Override
//    public Class getEntityClass() {
//        return this.getClass();
//    }
}
